package com.example.springbootpractice.responseBody;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

/*
实现: 统一数据返回
1. 需要使用注解 @ControllerAdvice
2. 然后使用实现接口 ResponseBodyAdvice
3. 然后重写 supports 方法 和 beforeBodyWrite
 */
@ControllerAdvice
@ResponseBody
public class ResponseAdvice implements ResponseBodyAdvice {
    @Override  // 返回 true 表示需要所有情况下都要使用 统一数据返回f
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 这里面的 body 就是我们原本返回的数据
        HashMap<String, Object> result = new HashMap<> ();
        result.put("state", "200");
        result.put("date", body);
        return result;
    }
}
